package com.echo.servlet.UserServlet;

import com.echo.service.UserService;
import com.echo.servlet.BaseServlet;
import com.echo.util.BusinessException;
import com.echo.entity.User;
import com.echo.util.SessionUtils;
import com.echo.util.BCryptUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

/**
 * 修改用户密码Servlet
 * 用于当前登录用户修改密码，需要原密码校验
 */
@WebServlet("/reset-password")
public class ResetPasswordServlet extends BaseServlet {
    private static final Logger logger = Logger.getLogger(ResetPasswordServlet.class.getName());
    private final UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置编码
        setRequestEncoding(request);
        
        // 设置响应类型为JSON
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        
        try {
            // 获取当前登录用户
            User currentUser = SessionUtils.getCurrentUser(request);
            if (currentUser == null) {
                out.write("{\"success\":false, \"message\":\"请先登录！\"}");
                return;
            }

            // 获取请求参数
            String oldPassword = request.getParameter("oldPassword");
            String newPassword = request.getParameter("newPassword");
            String confirmPassword = request.getParameter("confirmPassword");
            
            // 参数校验
            if (oldPassword == null || oldPassword.trim().isEmpty()) {
                out.write("{\"success\":false, \"message\":\"原密码不能为空！\"}");
                return;
            }

            if (newPassword == null || newPassword.trim().isEmpty()) {
                out.write("{\"success\":false, \"message\":\"新密码不能为空！\"}");
                return;
            }

            if (newPassword.length() < 6) {
                out.write("{\"success\":false, \"message\":\"密码长度不能少于6位！\"}");
                return;
            }

            if (confirmPassword == null || !newPassword.equals(confirmPassword)) {
                out.write("{\"success\":false, \"message\":\"两次输入的密码不一致！\"}");
                return;
            }
            
            // 添加日志记录，排查原密码校验问题
            logger.info("准备验证原密码，用户ID: " + currentUser.getId() + ", 用户名: " + currentUser.getUsername());
            logger.info("Session中的密码哈希值长度: " + (currentUser.getPassword() != null ? currentUser.getPassword().length() : "null"));
            logger.info("输入的原密码长度: " + oldPassword.length());
            
            // 检查Session中的密码哈希值是否有效
            boolean isValidHash = BCryptUtil.isValidHash(currentUser.getPassword());
            logger.info("密码哈希值格式是否有效: " + isValidHash);
            
            // 校验原密码
            boolean passwordMatch = BCryptUtil.checkPassword(oldPassword, currentUser.getPassword());
            logger.info("原密码校验结果: " + passwordMatch);
            
            if (!passwordMatch) {
                if (!isValidHash) {
                    logger.warning("密码校验失败：哈希值格式无效");
                    out.write("{\"success\":false, \"message\":\"密码格式不兼容，请联系管理员！\"}");
                } else {
                    logger.warning("密码校验失败：原密码输入错误");
                    out.write("{\"success\":false, \"message\":\"原密码输入错误！\"}");
                }
                return;
            }
            
            // 更新密码
            userService.updatePassword(currentUser.getId(), newPassword);
            
            // 返回成功响应
            out.write("{\"success\":true, \"message\":\"密码更新成功！请使用新密码重新登录。\"}");
            
        } catch (BusinessException e) {
            // 业务异常处理
            out.write("{\"success\":false, \"message\":\"" + e.getMessage().replaceAll("\\\"", "\\\\\"").replaceAll("\\n", "\\\\n") + "\"}");
        } catch (Exception e) {
            // 其他异常处理
            e.printStackTrace();
            out.write("{\"success\":false, \"message\":\"系统错误：" + e.getMessage().replaceAll("\\\"", "\\\\\"").replaceAll("\\n", "\\\\n") + "\"}");
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // GET请求使用父类的forward方法转发到密码修改页面
        forward(request, response, "/reset-password.html");
    }
}